package com.handydata.antifraud.channel.inbound;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.handydata.antifraud.bo.orderbaseinfo.OrderBaseInfoReqBO;
import com.handydata.antifraud.bo.orderbaseinfo.OrderBaseInfoResBO;
import com.handydata.antifraud.channel.RabbitSender;
import com.handydata.antifraud.channel.outbound.DataPusher;
import com.handydata.antifraud.enums.ProcessStatusEnum;
import com.handydata.antifraud.enums.RiskReturnEnum;
import com.handydata.antifraud.port.NumInterface;
import com.handydata.antifraud.rule.RuleEngineScheduler;
import com.handydata.antifraud.service.AlarmInfoService;
import com.handydata.antifraud.service.OrderBaseInfoService;
import com.handydata.antifraud.util.DateUtil;
import com.handydata.antifraud.util.IPUtil;
import com.handydata.antifraud.vo.orderbaseinfo.CreateOrderBaseInfoReqVO;
import com.handydata.common.convert.CommonBeanConvertor;
import com.handydata.common.util.RedisKey;
import com.handydata.common.util.RedisUtil;

/**
 * 数据接收器
 */
@Component
public class DataReceiver {

    private static final Logger logger = LoggerFactory.getLogger(DataReceiver.class);

    @Autowired
    private OrderBaseInfoService orderBaseInfoService;

    @Autowired
    private DataPusher dataPusher;

    @Autowired
    private RuleEngineScheduler ruleEngineScheduler;

    @Autowired
    private AlarmInfoService alarmInfoService;

    @Autowired
	private NumInterface numInterface;
    /**
     * 接收订单数据
     * @param createOrderBaseInfoReqVO
     */
    //@Transactional

    @Autowired
    private RabbitSender rabbitSender;

    @Autowired
    private RedisUtil redisUtil;
    
//    @Value("${spring.rabbitmq.queue}")
//    private String port;
    @Value("${server.port}")
    private String port;
    
//    private int num;

    @SuppressWarnings({ "unchecked", "rawtypes" })
	public String receiveData(CreateOrderBaseInfoReqVO createOrderBaseInfoReqVO) {

        OrderBaseInfoReqBO orderBaseInfoReqBO = CommonBeanConvertor.convert(createOrderBaseInfoReqVO, OrderBaseInfoReqBO.class);
//        logger.info("===============接收订单号orderId：{}",orderBaseInfoReqBO.getOrderId());
        allocate(orderBaseInfoReqBO);
        try {
            //alarmInfoService.startWatchTimeOut(AlarmInfoCode.ALERT_ITEM_ORDER.getCode(),orderBaseInfoReqBO.getOrderId(),null);
            String key="order_" + orderBaseInfoReqBO.getOrderId();
			Integer val = (Integer) redisUtil.get(key);
			if (val != null) {
				if (val == 2 || val == 4) {
                    logger.info("该订单号已经接收过,并执行成功，不再接收和执行{}",orderBaseInfoReqBO.getOrderId());//等着上行回查吧
                    return RiskReturnEnum.SUCCESS.getCode();
				} else if (val == 1) {
                    logger.info("该订单号已经接受过,并且正在执行，不再接受和执行{}",orderBaseInfoReqBO.getOrderId());//等着上行回查吧
                    return RiskReturnEnum.SUCCESS.getCode();
				} else if (val == 0) {
                    logger.info("该订单号{}已经接收过,等待执行，不再接收",orderBaseInfoReqBO.getOrderId());
                    return RiskReturnEnum.SUCCESS.getCode();
                } else { 
                    logger.info("该订单号{}已经接受过,但没有执行成功，重新执行",orderBaseInfoReqBO.getOrderId());
                    rabbitSender.send(JSON.toJSONString(orderBaseInfoReqBO),orderBaseInfoReqBO.getOrderId());
                    return RiskReturnEnum.SUCCESS.getCode();
                }
            } else {
            	OrderBaseInfoReqBO req = new OrderBaseInfoReqBO();
            	req.setOrderId(createOrderBaseInfoReqVO.getOrderId());
            	OrderBaseInfoResBO resBO = orderBaseInfoService.queryOrderBaseInfo(req);
            	logger.info("通过订单号查询数据库得到结果：{}",JSON.toJSONString(resBO));
            	if (resBO == null || resBO.getResultList().isEmpty()) {
            		orderBaseInfoService.saveDataToDbMqRedis(orderBaseInfoReqBO);//方法加了事务
            		// redis统计自然流量订单数
            		Map map = JSONObject.parseObject(createOrderBaseInfoReqVO.getRecieveData());
            		if (StringUtils.equals("FLOW022", (String) map.get("custTypeCode"))) {
						boolean isYes = redisUtil.hasKey(RedisKey.CUST_TYPE_CODE_KEY + "FLOW022");
						Map<String, Object> custTypeCodeMap = new HashMap<String, Object>();
						if(isYes){
							custTypeCodeMap = (Map<String, Object>)redisUtil.get(RedisKey.CUST_TYPE_CODE_KEY + "FLOW022");
							custTypeCodeMap.put("FLOW022",this.getSum("NUMFlOW022"));
							redisUtil.set(RedisKey.CUST_TYPE_CODE_KEY + "FLOW022", custTypeCodeMap);
						}else{
							custTypeCodeMap.put("FLOW022",this.getSum("NUMFlOW022"));
							redisUtil.set(RedisKey.CUST_TYPE_CODE_KEY + "FLOW022", custTypeCodeMap);
						}
    				} 
				} else {
					if (StringUtils.equals(resBO.getResultList().get(0).getProcessState(),"2") 
							|| StringUtils.equals(resBO.getResultList().get(0).getProcessState(),"4")) {
						logger.info("该订单号已经接收过,并执行成功，不再接收和执行{}",orderBaseInfoReqBO.getOrderId());//等着上行回查吧
						return RiskReturnEnum.SUCCESS.getCode();
					} else if (StringUtils.equals(resBO.getResultList().get(0).getProcessState(),"1")) {
						logger.info("该订单号已经接受过,并且正在执行，不再接受和执行{}",orderBaseInfoReqBO.getOrderId());//等着上行回查吧
						return RiskReturnEnum.SUCCESS.getCode();
					} else if (StringUtils.equals(resBO.getResultList().get(0).getProcessState(),"0")) {
						logger.info("该订单号{}已经接收过,等待执行，不再接收",orderBaseInfoReqBO.getOrderId());
						return RiskReturnEnum.SUCCESS.getCode();
					} else { //4发送成功，还要重新执行吗
						logger.info("该订单号{}已经接受过,但没有执行成功，重新执行",orderBaseInfoReqBO.getOrderId());//等着上行回查吧
						rabbitSender.send(JSON.toJSONString(orderBaseInfoReqBO),orderBaseInfoReqBO.getOrderId());
						return RiskReturnEnum.SUCCESS.getCode();
					}
				}
			} 
            return RiskReturnEnum.SUCCESS.getCode();

        }catch (Exception ex){
            logger.error("保存数据到到数据库，MQ，Redis失败",ex);
            return RiskReturnEnum.RISK_SYSTEM_ERROR.getCode();
        }

    }
    private void allocate(OrderBaseInfoReqBO orderBaseInfoReqBO) {
//    	logger.info("===============接收订单号orderId{}     2",orderBaseInfoReqBO.getOrderId());
        orderBaseInfoReqBO.setReceiveTime(DateUtil.localDateTimeToUdate());
        orderBaseInfoReqBO.setCreateTime(DateUtil.localDateTimeToUdate());
        orderBaseInfoReqBO.setProcessState(ProcessStatusEnum.PENDING.getCode());
        orderBaseInfoReqBO.setReceive_ip(IPUtil.getIpAddress() + ":" + port);//记录那台机器分发的
    }

	public long getSum(String param){
		return numInterface.getSum(param);
	}
}
